package com.cskaoyan.service.wx;

import com.cskaoyan.bean.bo.wjjBO.WXGoodsDetailBO;
import com.cskaoyan.bean.bo.wjjBO.WXGoodsListBo;
import com.cskaoyan.bean.bo.wjjBO.WXGoodsRelatedBO;
import com.cskaoyan.bean.common.Constant;
import com.cskaoyan.bean.marketBean.*;
import com.cskaoyan.bean.po.WXGoodsCategoryBO;
import com.cskaoyan.bean.po.example.WXGoodsListExamplePO;
import com.cskaoyan.bean.vo.wjjVO.*;
import com.cskaoyan.mapper.marketMapper.*;
import com.cskaoyan.bean.vo.wjjVO.WXGoodsCategoryVO;
import com.cskaoyan.bean.vo.wjjVO.WXGoodsListVO;
import com.cskaoyan.mapper.marketMapper.MarketCategoryMapper;
import com.cskaoyan.mapper.marketMapper.MarketGoodsMapper;
import com.cskaoyan.mapper.marketMapper.MarketSearchHistoryMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author wjj
 * @date 2022-12-31 13:28
 * @describe
 */
@Transactional
@Service
public class WXGoodsServiceImpl implements WXGoodsService {

    @Autowired
    MarketGoodsMapper goodsMapper;

    @Autowired
    MarketCategoryMapper categoryMapper;

    @Autowired
    MarketGoodsAttributeMapper goodsAttributeMapper;

    @Autowired
    MarketBrandMapper brandMapper;

    @Autowired
    MarketCommentMapper commentMapper;

    @Autowired
    MarketGrouponRulesMapper grouponRulesMapper;

    @Autowired
    MarketGrouponMapper grouponMapper;

    @Autowired
    MarketIssueMapper issueMapper;

    @Autowired
    MarketGoodsProductMapper goodsProductMapper;

    @Autowired
    MarketGoodsSpecificationMapper goodsSpecificationMapper;

    @Autowired
    MarketSearchHistoryMapper historyMapper;

    @Autowired
    MarketCollectMapper collectMapper;

    @Autowired
    MarketFootprintMapper footprintMapper;

    @Override
    public Integer selectGoodsCount() {
        Integer goodsCount = goodsMapper.selectGoodsCount();

        return goodsCount;
    }

    @Override
    public WXGoodsCategoryVO selectGoodsByCategoryId(WXGoodsCategoryBO goodsCategoryBO) {

        MarketCategory category = new MarketCategory();
        category.setId(goodsCategoryBO.getId());
        MarketCategory currentCategory = categoryMapper.selectCurrentMarketGoodsCategory(category);

        Integer pid = currentCategory.getPid();
        MarketCategory parentCategory = null;
        List<MarketCategory> brotherCategory = null;
        MarketCategory marketCategory = new MarketCategory();
        if (pid != 0) {
            category.setPid(pid);
            parentCategory = categoryMapper.selectParentMarketGoodsCategory(category);

            marketCategory.setPid(currentCategory.getPid());
            brotherCategory = categoryMapper.selectBrotherMarketCategory(marketCategory);
        } else {
            parentCategory = currentCategory;

            marketCategory.setPid(currentCategory.getId());
            brotherCategory = categoryMapper.selectBrotherMarketCategory(marketCategory);
        }

        WXGoodsCategoryVO goodsCategoryVO = new WXGoodsCategoryVO();
        goodsCategoryVO.setBrotherCategory(brotherCategory);
        goodsCategoryVO.setCurrentCategory(currentCategory);
        goodsCategoryVO.setParentCategory(parentCategory);

        return goodsCategoryVO;
    }


    @Override
    public WXGoodsListVO selectGoodsList(WXGoodsListBo goodsListBo) {
        WXGoodsListExamplePO goodsListExamplePO = new WXGoodsListExamplePO();
        String orderBy = null;
        if (goodsListBo.getOrder() != null && goodsListBo.getSort() != null) {
            orderBy = goodsListBo.getSort() + " " + goodsListBo.getOrder();
        }
        goodsListExamplePO.setOrderBy(orderBy);
        goodsListExamplePO.setCategoryId(goodsListBo.getCategoryId());
        goodsListExamplePO.setBrandId(goodsListBo.getBrandId());
        if (goodsListBo.getKeyword() != null) {
            if (!"".equals(goodsListBo.getKeyword().trim())) {
                goodsListExamplePO.setKeyWord("%" + goodsListBo.getKeyword() + "%");
            }
        }
        goodsListExamplePO.setIsNew(goodsListBo.getIsNew());
        goodsListExamplePO.setIsHot(goodsListBo.getIsHot());

        //分页插件 PageHelper，辅助我们做分页以及分页信息的获得
        PageHelper.startPage(goodsListBo.getPage(), goodsListBo.getLimit());
        //执行查询过程中拼接分页信息

        List<MarketGoods> goods = goodsMapper.selectGoodsLikeByName(goodsListExamplePO);

        //把keyword存到数据库当中去
        String keyword = goodsListBo.getKeyword();
        MarketSearchHistory history = new MarketSearchHistory();
        history.setAddTime(new Date());
        history.setUpdateTime(new Date());
        history.setDeleted(false);
        Integer userId = goodsListBo.getUserId();
        history.setUserId(userId);
        if (keyword != null) {
            history.setKeyword(keyword);
            if (userId != null){
                historyMapper.insertMarketHistory(history);
            }else {
                historyMapper.insertMarketHistoryWithOutUserId(history);
            }

        }
        // 将查询结果作为有参构造方法的形参传入，可以获得PageInfo
        PageInfo<MarketGoods> pageInfo = new PageInfo<>(goods);

        ArrayList<MarketCategory> filterCategoryList = new ArrayList<>();
        ArrayList<MarketCategory> categories = new ArrayList<>();
        for (MarketGoods good : goods) {

            List<MarketCategory> marketCategory = categoryMapper.selectMarketCategoryByPid(good.getCategoryId());
            categories.addAll(marketCategory);
        }
        for (MarketCategory category : categories) {
            if (!filterCategoryList.contains(category)) {
                filterCategoryList.add(category);
            }
        }

        WXGoodsListVO goodsListVO = new WXGoodsListVO();
        goodsListVO.setTotal((int) pageInfo.getTotal());
        goodsListVO.setPages(pageInfo.getPages());
        goodsListVO.setLimit(goodsListBo.getLimit());
        goodsListVO.setPage(goodsListBo.getPage());
        goodsListVO.setList(goods);
        goodsListVO.setFilterCategoryList(filterCategoryList);

        return goodsListVO;
    }

    @Override
    public WXGoodsDetailVO selectGoodsDetail(WXGoodsDetailBO goodsDetailBO) {
        Integer goodsId = goodsDetailBO.getId();

        MarketGoods goods = goodsMapper.selectByPrimaryKey(goodsId);
        List<MarketGoodsAttribute> goodsAttributeList = goodsAttributeMapper.selectGoodsAttributeListByGoodsId(goodsId);
        MarketBrand brand = brandMapper.selectMarketBrandById(goods.getBrandId());
        List<MarketComment> commentList = commentMapper.selectMarketCommentByGoodsId(goodsId);
        WXGoodsDetailCommentVO wxGoodsDetailCommentVO = new WXGoodsDetailCommentVO();
        wxGoodsDetailCommentVO.setCount(commentList.size());
        wxGoodsDetailCommentVO.setData(commentList);
        MarketGrouponRules grouponRules = grouponRulesMapper.selectMarketGoodsRulesByGoodSId(goodsId);
        List<MarketGroupon> grouponList = new ArrayList<>();
        if (grouponRules != null) {
            grouponList = grouponMapper.selectMarkGrouponby(grouponRules.getId());
        }
        List<MarketIssue> issue = issueMapper.selectMarketIssue();
        List<MarketGoodsProduct> productList = goodsProductMapper.selectMarketGoodsProductByGoodsId(goodsId);
        List<MarketGoodsSpecification> goodsSpecificationList = goodsSpecificationMapper.selectMarketGoodsSpecificationByGoods(goodsId);
        ArrayList<WXGoodsDetailSpecificationListVO> specifications = new ArrayList<>();
        if (goodsSpecificationList != null) {
            for (MarketGoodsSpecification marketGoodsSpecification : goodsSpecificationList) {
                List<MarketGoodsSpecification> specificationList = goodsSpecificationMapper.selectGoodsSpecByGoodsAndSpec(goodsId, marketGoodsSpecification.getSpecification());
                WXGoodsDetailSpecificationListVO wxGoodsDetailSpecificationListVO = new WXGoodsDetailSpecificationListVO();
                wxGoodsDetailSpecificationListVO.setName(marketGoodsSpecification.getSpecification());
                wxGoodsDetailSpecificationListVO.setValueList(specificationList);
                specifications.add(wxGoodsDetailSpecificationListVO);
            }
        }

        int setUserHasCollect = 0;
        Integer userId = goodsDetailBO.getUserId();
        Boolean share = true;
        if (userId != null){

            //根据userId和valueId查询collect表中所有的该用户收藏的商品
            int type = 0;
            MarketCollect marketCollect = new MarketCollect();
            marketCollect.setType((byte) type);
            marketCollect.setUserId(userId);
            List<MarketCollect> collectList = collectMapper.selectMarketCollectByTypeUserId(marketCollect);

            int count = 0;
            for (MarketCollect collect : collectList) {
                if (collect.getValueId().equals(goodsId)){
                    count++;
                }
            }
            if (count != 0){
                setUserHasCollect = 1;
            }
        }else {
            //userId为0时表示未登录,未登录状态禁止分享
            userId = Constant.WX_DEFAULT_USERID_CODE;
            share = Constant.WX_DEFAULT_SHARE_CODE;
        }

        Date date = new Date();
        MarketFootprint marketFootprint = new MarketFootprint();
        marketFootprint.setUserId(userId);
        marketFootprint.setGoodsId(goodsId);
        marketFootprint.setAddTime(date);
        marketFootprint.setUpdateTime(date);
        marketFootprint.setDeleted(false);
        goodsMapper.insertFootPrint(marketFootprint);

        WXGoodsDetailVO goodsDetailVO = new WXGoodsDetailVO();
        goodsDetailVO.setAttribute(goodsAttributeList);
        goodsDetailVO.setBrand(brand);
        goodsDetailVO.setComment(wxGoodsDetailCommentVO);
        goodsDetailVO.setGroupon(grouponList);
        goodsDetailVO.setInfo(goods);
        goodsDetailVO.setIssue(issue);
        goodsDetailVO.setProductList(productList);

        goodsDetailVO.setShare(share);
        goodsDetailVO.setShareImage(goods.getShareUrl());
        goodsDetailVO.setSpecificationList(specifications);

        goodsDetailVO.setUserHasCollect(setUserHasCollect);
        return goodsDetailVO;
    }

    @Override
    public WXGoodsRelatedVO selectGoodsRelatedById(WXGoodsRelatedBO goodsRelatedBO) {
        MarketGoods marketGoods = new MarketGoods();
        marketGoods.setId(goodsRelatedBO.getId());
        MarketGoods goods = goodsMapper.selectGoodsById(marketGoods);
        //暂定page为1,limit为6
        //分页插件 PageHelper，辅助我们做分页以及分页信息的获得

        PageHelper.startPage(Constant.WX_GOODS_PAGE_CODE, Constant.WX_GOODS_LIMIT_CODE);
        //执行查询过程中拼接分页信息

        //获取同类商品的人气推荐商品的前6个商品
        List<MarketGoods> marketGoodsList = goodsMapper.selectHotMarketGoodsByCategoryId(goods);

        // 将查询结果作为有参构造方法的形参传入，可以获得PageInfo
        PageInfo<MarketGoods> pageInfo = new PageInfo<>(marketGoodsList);

        WXGoodsRelatedVO goodsRelatedVO = new WXGoodsRelatedVO();
        goodsRelatedVO.setTotal((int) pageInfo.getTotal());
        goodsRelatedVO.setPages(pageInfo.getPages());
        goodsRelatedVO.setLimit(Constant.WX_GOODS_LIMIT_CODE);
        goodsRelatedVO.setPage(Constant.WX_GOODS_PAGE_CODE);
        goodsRelatedVO.setList(marketGoodsList);

        return goodsRelatedVO;
    }
}
